package com.lingx.web.api.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.model.impl.DefaultEntity;
import com.lingx.model.impl.tools.ModelIO;
import com.lingx.service.LingxService;
import com.lingx.service.ModelService;
import com.lingx.utils.Utils;
import com.lingx.web.api.IApi;
@Component
public class Api8009 extends AbstractApi implements IApi{
	@Resource
	private LingxService lingxService;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private ModelService modelService;
	@Override
	public int getApiCode() {
		return 8009;
	}
	@Override
	public String getApiName() {
		return "接收远程模型";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String hexstring=IApi.getParamString(params, "model", "");
		String secret1=IApi.getParamString(params, "secret", "");
		String enabled=this.lingxService.getConfigValue("lingx.update.enabled", "none");
		String secret2=this.lingxService.getConfigValue("lingx.update.secret", "none");
		if("true".equals(enabled)&&secret2.equals(secret1)) {
			byte[] data=Api9028.hexToBytes(hexstring);
			Object obj=Api9028.toObject(data);
			DefaultEntity entity=(DefaultEntity)obj;
			handler(entity,this.jdbcTemplate);
			data=null;
		}else {
			ret.put("code", -1);
			ret.put("enabled", enabled);
		}
		return ret;
	}

	public void handler(DefaultEntity entity,JdbcTemplate jdbc) {
		try {
			ModelService.ENTITY_CACHE.put(entity.getCode(), entity);
			ModelIO.writeEntity(entity, jdbc);
			if(jdbc.queryForObject("select count(*) from tlingx_entity where code=?",Integer.class,entity.getCode())==0){
				jdbc.update("insert into tlingx_entity(id,name,code,type,status,app_id,create_time)values(uuid(),?,?,1,1,?,?)",entity.getName(),entity.getCode(),"335ec1fc-1011-11e5-b7ab-74d02b6b5f61",Utils.getTime());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

}
